<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>留言板</title>
    </head>
    <body>
        <h1>简单留言板</h1>
        <div class="container">
            <form class="message" action="index.php" method="post">
                <p>
                    <label for="author">昵称：<input type="text" name="author" value=""></label>
                </p>
                <p>
                    <label for="content">内容：<textarea name=
                        "content" rows="5" cols="40"></textarea></label>
                </p>
                <p>
                    <input type="submit" name="submit" value="提交">
                </p>
            </form>
            <?php
                $filename = "message.txt";
                // 提交表单
                if(isset($_POST['submit'])) {
                    $message = $_POST['author']."||".$_POST['content']."[n]";
                    writemyfile($filename, $message);
                }
                // 写文件
                function writemyfile($filename, $message) {
                    $fp = fopen($filename, "a");
                    if(flock($fp, LOCK_EX | LOCK_NB)){
                        fwrite($fp, $message);
                        flock($fp, LOCK_UN | LOCK_NB);
                    }
                    fclose($fp);
                }
                if(file_exists($filename)) {
                    readmyfile($filename);
                }
                function readmyfile($filename) {
                    // $message = file_get_contents($filename);

                    $message = "";

                    $fp =  fopen($filename, "r");
                    // 如果锁定失败，提示错误并停止执行
                    if(!flock($fp, LOCK_EX | LOCK_NB)){
                        echo "Unable to obtain lock";
                        exit;
                    }
                    // 读取文件内容
                    while(!feof($fp)) {
                        $message .= fread($fp, 1024);
                    }
                    // 释放
                    flock($fp, LOCK_UN | LOCK_NB);

                    $message = rtrim($message, "[n]");
                    $message_array = explode("[n]", $message);
                    foreach ($message_array as $text) {
                        list($author, $content) = explode("||", $text);
                        echo "<h5> {$author}</h5> <p>{$content}</p>";
                    }

                    fclose($fp);
                }

             ?>
        </div>
    </body>
</html>
